package dao;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.text.format.Time;
import android.util.Log;
import beans.Alarm;

public class DaoAlarm implements DaoAlarmInterface{
	private Context context;
	
	public DaoAlarm(Context c){
		context = c;
	}
	
	public void save(Alarm alarm) {
		try {
    		ObjectOutputStream alarmOOS= new ObjectOutputStream(context.openFileOutput("alarm.serial",Context.MODE_PRIVATE));
			alarmOOS.writeObject(alarm);
			alarmOOS.flush();
			alarmOOS.close();
		}
    	catch(IOException ioe) {

    		Log.i("DaoAlarm", "Ioe exception lors de l'ecriture");
			ioe.printStackTrace();
		}
		
	}

	public Alarm getSavedAlarm() {
		Alarm alarm = null;
		try {
    		ObjectInputStream alarmOIS= new ObjectInputStream(context.openFileInput("alarm.serial"));
    		alarm = (Alarm) alarmOIS.readObject(); 
    		alarmOIS.close();
		}
    	catch(FileNotFoundException fnfe){
    		Log.i("DaoAlarm", "file not found lors du chargement");
    	}
    	catch(IOException ioe) {
    		Log.i("DaoAlarm", "ioe Exceptioon");
			ioe.printStackTrace();
		}
    	catch(ClassNotFoundException cnfe) {

    		Log.i("DaoAlarm", "Class not found ");
			cnfe.printStackTrace();
		}
		
		//Si on a eu un probleme, on set une valeur par default a notre alarme
		if(alarm == null){
			alarm = new Alarm(null);
        	alarm.setActive(context,false);
        	Time t = new Time();
        	t.hour = 7;
        	t.minute = 30;
        	alarm.setHeure(t);
		}
		
		return alarm;
	}

}
